package cn.bluedot.tea.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.bluedot.framework.annotations.Dispatcher;
import cn.bluedot.framework.annotations.RequestView;
import cn.bluedot.framework.annotations.ResponseJson;
import cn.bluedot.framework.annotations.Service;
import cn.bluedot.framework.service.BaseService;
import cn.bluedot.framework.web.Result;
import cn.bluedot.tea.dao.BaseDao;
import cn.bluedot.tea.pojo.domain.Menu;
import cn.bluedot.tea.pojo.domain.Role;
import cn.bluedot.tea.pojo.domain.User;
import cn.bluedot.tea.pojo.domain.Ztree;
import cn.bluedot.tea.util.Page;
import cn.bluedot.tea.util.PageBean;

@Service
public class RoleService extends BaseService{

	public RoleService(){}
	
	public RoleService(String uri, Map<String, Object[]> params, Map<String, Object> data) {
		super(params, data);
		execute(uri, params, data); 
	}
	
	@RequestView(uri="/system/role/list", view="getRoleList")
	@Dispatcher(success="/system/role/role", failed="/error")
	private void getRoleList(Map<String, Object[]> params, Map<String, Object> data) throws Exception  {
		Map<String, Object> param = getParameterMap(params);
		
		String num = (String) param.get("pagenum");
		param.remove("pagenum");
		int pagenum = num == null ? 1 : Integer.parseInt(num);
		
		Page.startPage(pagenum, 10);
		
		List<?> query = (List<?>) BaseDao.excuteQuery(param, null);
		
		PageBean<?> pageBean = new PageBean<>(query, 10);
		
		data.put("query", pageBean);
		data.put("RESULT", Result.SUCCESS);
		
	}
	
	@RequestView(uri="/system/role/add")
	@ResponseJson
	private void addRole(Map<String, Object[]> params, Map<String, Object> data) throws Exception  {
		
		String[] menuIds = ((String) params.get("menuIds")[0]).split(",");
		
		params.remove("menuIds");
		
		Map<String, Object> param = getParameterMap(params);
		
		Object roleDecs = param.get("roleDecs");
		
		/**
		 * 1.查询角色名称和字符是否存在
		 * 2.查询角色数量
		 * 3.新增角色信息
		 * 4.给角色新增权限信息
		 */
		param.remove("roleDecs");
		param.put("view", "checkRole");
		
		int query = (int) BaseDao.excuteQuery(param, null);
		
		if(query == 1) {
			data.put("message", "角色名称或权限字符已存在");
			data.put("RESULT", Result.FAILED);
		} else {
			
			//插入
			param.put("view", "insertRole");
			param.put("roleDecs", roleDecs); //param中参数：view、roleName、roleKey、roleDecs
			
			int excute = BaseDao.excute(param);
			
			if(excute == 0) {
				data.put("message", "操作失败");
				data.put("RESULT", Result.FAILED);
			}else {
				
				param.remove("roleDecs");
				param.put("view", "getRoleId");
				int roleId = (int) BaseDao.excuteQuery(param, null);
				
				param.clear();
				param.put("roleId", roleId);
				//批处理（没做），直接用插入，出错随缘
				for (int i = 0; i < menuIds.length; i++) {
					param.put("view", "insertRoleMenu");
					param.put("menuId", menuIds[i]);
					BaseDao.excute(param);
				}
				data.put("message", "操作成功");
				data.put("RESULT", Result.SUCCESS);
			}	
		}
		
	}
	
	@RequestView(uri="/system/role/delete")
	@ResponseJson
	private void deleteRole(Map<String, Object[]> params, Map<String, Object> data) throws Exception  {
		Map<String, Object> param = getParameterMap(params);
		
		/**
		 * 1.查询是否分配用户
		 * 2.删除角色信息
		 * 3.级联删除角色权限关联表信息
		 */
		Object roleId = param.get("roleId");
		param.put("view", "selectUserCountByRole");
		
		int query = (int) BaseDao.excuteQuery(param, null);
		
		if(query > 0) {
			data.put("message", "角色已分配,不能删除");
			data.put("RESULT", Result.FAILED);
		}else {
			
			param.put("view", "deleteRole");
			
			int excute = BaseDao.excute(param);
			if(excute > 0) {
				data.put("message", "操作成功");
				data.put("RESULT", Result.SUCCESS);
			}else {
				data.put("message", "操作失败");
				data.put("RESULT", Result.FAILED);
			}
		}
	}
	
	@RequestView(uri="/system/role/get_role", view="getRoleById")
	@Dispatcher(success="/system/role/edit", failed="/error")
	private void getRole(Map<String, Object[]> params, Map<String, Object> data) throws Exception  {
		Map<String, Object> param = getParameterMap(params);
		
		Role role = (Role) BaseDao.excuteQuery(param, Role.class);
		
		data.put("role", role);
		data.put("RESULT", Result.SUCCESS);
		
	}
	
	@RequestView(uri="/system/role/get_user", view="getUserByRole")
	@Dispatcher(success="/system/role/authuser", failed="/error")
	private void getUser(Map<String, Object[]> params, Map<String, Object> data) throws Exception  {
		Map<String, Object> param = getParameterMap(params);
		
		List<User> list = (List<User>) BaseDao.excuteQuery(param, User.class, true);
		
		data.put("list", list);
		data.put("RESULT", Result.SUCCESS);
		
	}
	
	@RequestView(uri="/system/role/select", view="getUserWithRole")
	@Dispatcher(success="/system/role/select", failed="/error")
	private void getSelectUser(Map<String, Object[]> params, Map<String, Object> data) throws Exception  {
		Map<String, Object> param = getParameterMap(params);
		Object roleId = param.get("roleId");
		
		param.remove("roleId");
		
		List<?> list = (List<?>) BaseDao.excuteQuery(param, null, true);
		
		data.put("roleId", roleId);
		data.put("list", list);
		data.put("RESULT", Result.SUCCESS);
		
	}
	
	@SuppressWarnings("unchecked")
	@RequestView(uri="/system/role/edit")
	@ResponseJson
	private void editRole(Map<String, Object[]> params, Map<String, Object> data) throws Exception  {
		
		String[] menuIds = ((String) params.get("menuIds")[0]).split(",");
		params.remove("menuIds");
		
		Map<String, Object> param = getParameterMap(params);
		
		Object roleId = param.get("roleId");
		Object roleName = param.get("roleName");
		Object roleKey = param.get("roleKey");
		Object roleDecs = param.get("roleDecs");
		/**
		 * 1.查询角色名称和字符是否存在,如果用户没有修改名称和权限字符，则判断菜单权限是否修改
		 * 	 如果修改了名称和权限字符，则查询角色名称和权限字符是否存在
		 * 2.更新角色信息
		 * 3.给角色更新权限信息
		 */
		
		param.clear();
		param.put("view", "getRoleById");
		param.put("roleId", roleId);
		
		Role role = (Role) BaseDao.excuteQuery(param, Role.class);
		
		boolean check = role.getRoleName().equals(roleName) && role.getRoleKey().equals(roleKey);
		
		param.clear();
		param.put("view", "checkRole");
		param.put("roleName", roleName);
		param.put("roleKey", roleKey);
		
		int query = (int) BaseDao.excuteQuery(param, null); //roleName,roleKey
				
		if(query == 1 && !check) {
			data.put("message", "角色名称或权限字符已存在");
			data.put("RESULT", Result.FAILED);
		} else {
			//更新
			param.clear();
			param.put("view", "updateRole");
			param.put("roleId", roleId);
			param.put("roleName", roleName);
			param.put("roleKey", roleKey);
			param.put("roleDecs", roleDecs); 
			
			int excute = BaseDao.excute(param);
						
			if(excute == 0) {
				data.put("message", "操作失败");
				data.put("RESULT", Result.FAILED);
			}else {
				
				param.clear();
				param.put("view", "getRoleMenuCountById");
				param.put("roleId", roleId);
				int count = (int) BaseDao.excuteQuery(param, null);
				param.clear();
				param.put("view", "deleteRoleMenuById");
				param.put("roleId", roleId);
				//先删除当前roleId对应的menuId,再新增
				int delete = BaseDao.excute(param);
				if(delete > 0 && count != 0 || delete == 0 && count == 0) {
					for (int i = 0; i < menuIds.length; i++) {
						param.put("view", "insertRoleMenu");
						param.put("menuId", menuIds[i]);
						BaseDao.excute(param);
					}
				}
				data.put("message", "操作成功");
				data.put("RESULT", Result.SUCCESS);
			}	
		}
		
	}
	
	@RequestView(uri="/system/role/cancle", view="updateUserRole")
	@ResponseJson
	private void cancleUserRole(Map<String, Object[]> params, Map<String, Object> data) throws Exception {
		Map<String, Object> param = getParameterMap(params);
		
		param.put("roleId", 5); //设置为游客
		
		int excute = BaseDao.excute(param);
		
		if(excute == 0) {
			data.put("message", "操作失败");
			data.put("RESULT", Result.FAILED);
		}else {
			data.put("message", "操作成功");
			data.put("RESULT", Result.SUCCESS);
		}		
	}
	
	@RequestView(uri="/system/role/auth_user", view="updateUserRole")
	@ResponseJson
	private void authUser(Map<String, Object[]> params, Map<String, Object> data) throws Exception {
		
		Object[] userIds = params.get("userIds[]");
		params.remove("userIds");
		Map<String, Object> param = getParameterMap(params);
		
		for (int i = 0; i < userIds.length; i++) {
			param.put("view", "updateUserRole");
			param.put("userId", userIds[i]);
			BaseDao.excute(param);
		}
		
		data.put("message", "操作成功");
		data.put("RESULT", Result.SUCCESS);
	}
	
	
	//加载角色菜单列表数
	@RequestView(uri="/system/menu/roleTree", view="getMenuTreeByRole")
	@ResponseJson
	private void getMenuTreeByRole(Map<String, Object[]> params, Map<String, Object> data) throws Exception  {
		Map<String, Object> param = getParameterMap(params);
		
		List<Menu> menuRoleList = (List<Menu>) BaseDao.excuteQuery(param, Menu.class);
		List<String> roleMenuList = getRoleMenuList(menuRoleList);
		
		param.clear();
		param.put("view", "getMenuList");
		
		List<Menu> menuList = (List<Menu>) BaseDao.excuteQuery(param, Menu.class);
		List<Ztree> ztree = initZtree(menuList, roleMenuList);
		data.put("ztree", ztree);		
	}
	 
	//加载所有菜单列表树
	@RequestView(uri="/system/menu/tree")
	@ResponseJson
	private void getMenuTree(Map<String, Object[]> params, Map<String, Object> data) throws Exception  {
		Map<String, Object> param = getParameterMap(params);
		
		param.put("view", "getMenuList");
		
		List<Menu> list = (List<Menu>) BaseDao.excuteQuery(param, Menu.class);
		
		List<Ztree> ztree = initZtree(list);
		data.put("ztree", ztree);		
	}
	
	
	/**
	 * 初始化ztree
	 * @param list
	 * @return
	 */
	private List<Ztree> initZtree(List<Menu> list) {
		return initZtree(list, null, true);
	}
	
	private List<Ztree> initZtree(List<Menu> list, List<String> roleMenuList) {
		return initZtree(list, roleMenuList, true);
	}
	
	/**
	 * 对象转菜单树
	 * 
	 * @param menuList 菜单列表
	 * @param roleMenuList 角色已存在菜单列表
	 * @param permsFlag 是否需要显示权限标识
	 * @return 树结构列表
	 */
	private List<Ztree> initZtree(List<Menu> menuList, List<String> roleMenuList, boolean permsFlag){
		List<Ztree> ztrees = new ArrayList<Ztree>();
		boolean isCheck = roleMenuList == null ? false : (!roleMenuList.isEmpty());
		for (Menu menu : menuList){
			Ztree ztree = new Ztree();
			ztree.setId(menu.getMenuId());
			ztree.setpId(menu.getParentId());
			ztree.setName(transMenuName(menu, roleMenuList, permsFlag));
			ztree.setTitle(menu.getMenuName());
			if(isCheck) {
				ztree.setChecked(roleMenuList.contains(menu.getMenuId()+""));
			}
			ztrees.add(ztree);
		}
		return ztrees;
	}


	private String transMenuName(Menu menu, List<String> roleMenuList, boolean permsFlag){
		StringBuffer sb = new StringBuffer();
		sb.append(menu.getMenuName());
		if (permsFlag){
			sb.append("<font color=\"#888\">&nbsp;&nbsp;&nbsp;" + menu.getPerms() + "</font>");
		}
		return sb.toString();
	}
	
	/**
	 * 组装menuList字符串
	 * @param menuList
	 * @return
	 */
	private List<String> getRoleMenuList(List<Menu> menuList){
		
		if(menuList == null)
			return null;
		
		List<String> list = new ArrayList<>();
		
		for (Menu menu : menuList) {
			list.add(menu.getMenuId()+"");
		}
		
		return list;
	}
}